/**
 *Copyright (c) 2024 watereyes
 * workflow is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.workflow.api.listener;

import java.util.List;
import java.util.Objects;

import org.activiti.engine.EngineServices;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.delegate.event.ActivitiEvent;
import org.activiti.engine.delegate.event.impl.ActivitiEntityEventImpl;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.koron.ebs.mybatis.SessionFactory;

import com.koron.workflow.api.bean.RelationBean;
import com.koron.workflow.api.service.ActivitiService;
import com.koron.workflow.api.service.RelationService;
import com.koron.workflow.api.service.TaskListService;
import com.koron.workflow.common.util.SessionFactoryLocal;
import com.koron.workflow.common.util.SpringContextHolder;

public class TaskRejectCreatedListener extends ProcessListenerAdapter{
	
	private ActivitiService activitiService = SpringContextHolder.getBean(ActivitiService.class);
	
	private TaskListService taskListService = SpringContextHolder.getBean(TaskListService.class);
	
	private RelationService relationService = SpringContextHolder.getBean(RelationService.class);
	
	@Override
	public void taskCreatetd(ActivitiEvent event) {
		EngineServices engineServices = event.getEngineServices();
		RuntimeService runtimeService = engineServices.getRuntimeService();
		HistoryService historyService = engineServices.getHistoryService();
		if(event instanceof ActivitiEntityEventImpl) {
			ActivitiEntityEventImpl activitiEntity = (ActivitiEntityEventImpl) event;
			Object object = activitiEntity.getEntity();
			if(object instanceof TaskEntity) {
				TaskEntity entity = (TaskEntity) object;
				String title = (String) runtimeService.getVariable(event.getExecutionId(), "title");
				String operation = (String) runtimeService.getVariable(event.getExecutionId(), "operation");
				if(operation != null && "1".equals(operation)) {
					SessionFactory factory = SessionFactoryLocal.get();
					if(activitiService.isDraftNode(entity)) {
						HistoricProcessInstance processInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(event.getProcessInstanceId()).singleResult();
						//添加关系列表
						activitiService.addCandidateUser(entity.getId(), processInstance.getStartUserId());
						relationService.addRelation(factory, 512, new RelationBean(RelationBean.R_HANDLE, processInstance.getStartUserId(), entity.getProcessInstanceId(), entity.getId(), RelationBean.STATUS_UNHANDLE), null);
						//添加任务列表
						taskListService.addTaskList(factory, entity, title);
					}
					if(activitiService.isApprovalNode(entity)) {
						String mode = activitiService.getCirculationMode(entity);
						//先删除候选人员列表
						activitiService.deleteCandidateUsers(entity.getId());
						if("2".equals(mode) || "3".equals(mode)) { //串行 或者 会审
							String variableName = "Loop" + entity.getTaskDefinitionKey().replaceAll("-", "") + "_User_List";
							List<String> usersList = runtimeService.getVariable(event.getExecutionId(), variableName, List.class);
							Object loopCounter = runtimeService.getVariable(event.getExecutionId(), "loopCounter");
							int index = loopCounter == null ? 0 : Integer.parseInt(Objects.toString(loopCounter));
							runtimeService.setVariable(event.getExecutionId(), "index", index);
							//添加关系列表
							activitiService.addCandidateUser(entity.getId(), usersList.get(index));
							relationService.addRelation(factory, 512, new RelationBean(RelationBean.R_HANDLE, usersList.get(index), entity.getProcessInstanceId(), entity.getId(), RelationBean.STATUS_UNHANDLE), null);
						}else {
							List<HistoricTaskInstance> hisTasks = historyService.createHistoricTaskInstanceQuery().processInstanceId(event.getProcessInstanceId()).taskDefinitionKey(entity.getTaskDefinitionKey()).orderByHistoricTaskInstanceEndTime().desc().list();
							if(hisTasks != null && hisTasks.size() > 0) {
								activitiService.addCandidateUser(entity.getId(), hisTasks.get(0).getAssignee());
								relationService.addRelation(factory, 512, new RelationBean(RelationBean.R_HANDLE, hisTasks.get(0).getAssignee(), entity.getProcessInstanceId(), entity.getId(), RelationBean.STATUS_UNHANDLE), null);
							}
						}
						//添加任务列表
						taskListService.addTaskList(factory, entity, title);
					}
					//假如是子流程节点
					if(activitiService.isSubTaskNode(entity)) {
						activitiService.addCandidateUser(entity.getId(), "system_operation");
						relationService.addRelation(factory, 512, new RelationBean(RelationBean.R_HANDLE, "system_operation", entity.getProcessInstanceId(), entity.getId(), RelationBean.STATUS_UNHANDLE), null);
						//添加任务列表
						taskListService.addTaskList(factory, entity, title);
					}
				}
			}
		}
	}

}
